import theAxios from 'axios'
import router from '@/router'
import { Toast } from 'vant'
import { getToken } from './token'
const axios = theAxios.create({
  baseURL: 'http://toutiao.itheima.net/',
  timeout: 20000
})
// 请求拦截器
axios.interceptors.request.use(function (config) {
  if (getToken()?.length > 0 && config.headers.Authorization === undefined) {
    config.headers.Authorization = `Berar ${getToken()}`
  }
  return config
})
// 响应拦截器
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (error.response.status === 401) {
    Toast.fail('身份已过期！')
    const timer = setTimeout(function () {
      router.replace('/login')
      clearTimeout(timer)
    }, 2000)
  }
  return Promise.reject(error)
})
export default ({ url, method = 'GET', params = {}, data = {}, headers = {} }) => {
  return axios({
    url,
    method,
    params,
    data,
    headers
  })
}
